'''
作者：小鹿
个人网站：https://www.siena.zone
创作日期：2020年5月
'''
import Files.UI_watermark_Opt as IWM
import Files.Img_04_WaterMark as funcWM
import Files.Img_04_WaterMark_WMConvert as wmConv
from PyQt5.QtWidgets import *
import sys, cv2, os, time
import numpy as np
import numpy.core._dtype_ctypes
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.QtCore import *

class Watermark_Demo_UI(QWidget):


    def __init__(self):
        super(Watermark_Demo_UI, self).__init__()

        self.watermark_info = []
        self.imgList = []
        self.img_save_path = []
        self.img_save_name = []
        self.wm_before = None

        self.Demo = IWM.Watermark_Main_UI()
        self.Demo.Signal.connect(self.demonstrateImage)
        self.Demo.Signal_img_list.connect(self.InitImgsList)
        self.Wm_Start = WM_Operation_start()
        self.Wm_Start.WM_Signal.connect(self.Progress)
        self.Wm_Start.WM_Progress_signal.connect(self.ProgressBarStatus)
        self.Wm_Start.WM_Stop_Signal.connect(self.Finished)
        self.Wm_Convert = WM_Convert()
        self.Wm_Convert.wm_as_array.connect(self.OptWMDemo)
        self.Wm_Convert.wm_pbvalue_n_optcode.connect(self.OptWMProgress)

        self.palette = QPalette()
        self.palette.setColor(QPalette.Background, QColor(74, 74, 74))
        self.Demo.setPalette(self.palette)

        self.setWindowTitle('图像批处理——添加水印')
        self.setFixedSize(1000, 650)

        self.ImageUILeft()
        self.ImageUIRight()
        self.ImageWMRight()
        self.ImageUIShow()
        self.ShowFunc()
        self.StartFunc()
        self.ProgresBar()
        self.LayoutImgSetup()

    def ImageUILeft(self):

        self.imgFrameImglLayout = QHBoxLayout()
        self.imgFrameImglLayout_asWidget = QWidget()
        self.imgFrameImglLayout.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgFrameImgl = QLabel()
        self.imgFrameImgl.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgFrameImgl.setFixedSize(200, 400)
        self.imgFrameImgl.setText('点击"设置"按钮\n\n批量加水印')
        self.imgFrameImgl.setWordWrap(True)
        self.imgFrameImgl.setStyleSheet("background:#3F3F3F;padding-left:10px;padding-right:10px;")
        self.imgFrameImgl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.imgFrameImglLayout.addWidget(self.imgFrameImgl)
        self.imgFrameImglLayout_asWidget.setLayout(self.imgFrameImglLayout)
        self.imgFrameImglLayout_asWidget.setStyleSheet("background:#2F2F2F;color:#FFFFFF;")


        self.imgLeftBoxLayout = QHBoxLayout()
        self.imgLeftBoxLayout.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgLeftBoxLayout_asWidget = QWidget()
        self.imgLeftText = QLineEdit()
        self.imgLeftText.setEnabled(False)
        self.imgLeftText.setFixedWidth(120)
        self.imgLeftText.setText('摘要')
        self.imgLeftText.setFixedSize(120, 15)
        self.imgLeftText.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgLeftBoxLayout.addWidget(self.imgLeftText)
        self.imgLeftBoxLayout_asWidget.setLayout(self.imgLeftBoxLayout)

    def ImageUIRight(self):
    
        self.path_redirected = './Images/Splash.png'

        self.imgFrameImgrLayout = QHBoxLayout()
        self.imgFrameImgrLayout_asWidget = QWidget()
        self.imgFrameImgrLayout_asWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.imgFrameImgrLayout.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgFrameImgr = QLabel()
        self.imgFrameImgr.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgFrameImgr.setFixedSize(400, 400)
        self.imgFrameImgr.setText('若无黑底白色水印\n\n请打开黑底彩色水印\n\n以使批量加水印\n\n可以呈现镂空水印效果\n\n请勿转换透明水印')
        self.imgFrameImgr.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.imgFrameImgr.setStyleSheet('border-image:url(%s/Images/MainUI_WatermarkPanel.png)' % self.path_redirected)
        self.imgFrameImgrLayout.addWidget(self.imgFrameImgr)
        self.imgFrameImgrLayout_asWidget.setLayout(self.imgFrameImgrLayout)
        self.imgFrameImgrLayout_asWidget.setStyleSheet("background:#2F2F2F;color:#FFFFFF;")

        self.imgRightBoxLayout = QHBoxLayout()
        self.imgRightBoxLayout.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgRightBoxLayout_asWidget = QWidget()
        self.imgRightText = QLineEdit()
        self.imgRightText.setText('水印转换')
        self.imgRightText.setEnabled(False)
        self.imgRightText.setFixedSize(300, 15)
        self.imgRightText.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.imgRightBoxLayout.addWidget(self.imgRightText)
        self.imgRightBoxLayout_asWidget.setLayout(self.imgRightBoxLayout)

    def ImageWMRight(self):

        self.wmFrameLayout = QVBoxLayout()
        self.wmFrameLayout_asWidget = QWidget()
        self.wmFrameLayout_asWidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        self.wmFrameLayoutUp = QVBoxLayout()
        self.wmFrameLayoutUp.setAlignment(Qt.AlignCenter | Qt.AlignTop)

        self.wmOpenLayout = QHBoxLayout()
        self.wmOpenLayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.wmOpen = QPushButton('打开水印')
        self.wmOpen.setToolTip("选择需要转换的水印")
        '''self.opt_start.clicked.connect(self.xxx)'''
        '''self.opt_start.clicked.connect()'''
        self.wmOpen.setEnabled(True)
        self.wmOpen.clicked.connect(self.OptWMOpen)
        self.wmOpen.setFixedSize(120, 32)
        self.wmOpenLayout.addWidget(self.wmOpen)

        self.wmConvertLayout = QHBoxLayout()
        self.wmConvertLayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.wmConvert = QPushButton('转换水印')
        self.wmConvert.setToolTip("开始转换水印")
        '''self.opt_start.clicked.connect(self.xxx)'''
        '''self.opt_start.clicked.connect()'''
        self.wmConvert.setEnabled(False)
        self.wmConvert.clicked.connect(self.OptWMConvert)
        self.wmConvert.setFixedSize(120, 32)
        self.wmConvertLayout.addWidget(self.wmConvert)

        self.wmSaveLayout = QHBoxLayout()
        self.wmSaveLayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.wmSave = QPushButton('保存水印')
        self.wmSave.setToolTip("保存转换后的水印")
        '''self.opt_start.clicked.connect(self.xxx)'''
        '''self.opt_start.clicked.connect()'''
        self.wmSave.setEnabled(False)
        self.wmSave.clicked.connect(self.OptWMSave)
        self.wmSave.setFixedSize(120, 32)
        self.wmSaveLayout.addWidget(self.wmSave)

        self.wmFrameLayoutUpPlaceHolder = QWidget()
        self.wmFrameLayoutUpPlaceHolder.setFixedHeight(16)

        self.wmConvStatusLayout = QHBoxLayout()
        self.wmConvStatusLayout.setAlignment(Qt.AlignRight| Qt.AlignVCenter)
        self.wmConvStatus = QLineEdit()
        self.wmConvStatus.setEnabled(False)
        self.wmConvStatus.setFixedWidth(120)
        self.wmConvStatus.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.wmConvStatus.setText('未添加水印')
        self.wmConvStatusLayout.addWidget(self.wmConvStatus)

        self.wmConvProgressLayout = QHBoxLayout()
        self.wmConvProgressLayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.wmConvProgress = QProgressBar()
        self.wmConvProgress.setFixedSize(120, 8)
        self.wmConvProgress.setMinimum(0)
        self.wmConvProgress.setMaximum(3)
        self.wmConvProgress.setTextVisible(False)
        self.wmConvProgress.setVisible(False)
        self.wmConvProgressLayout.addWidget(self.wmConvProgress)

        self.wmFrameLayoutUp.addLayout(self.wmOpenLayout)
        self.wmFrameLayoutUp.addLayout(self.wmConvertLayout)
        self.wmFrameLayoutUp.addLayout(self.wmSaveLayout)
        self.wmFrameLayoutUp.addWidget(self.wmFrameLayoutUpPlaceHolder)
        self.wmFrameLayoutUp.addLayout(self.wmConvStatusLayout)
        self.wmFrameLayoutUp.addLayout(self.wmConvProgressLayout)

        self.wmFrameLayoutDown = QVBoxLayout()
        self.wmFrameLayoutDown.setAlignment(Qt.AlignRight | Qt.AlignBottom)

        self.wmCancel = QPushButton('取消转换')
        self.wmCancel.setToolTip("取消水印转换")
        '''self.opt_start.clicked.connect(self.xxx)'''
        '''self.opt_start.clicked.connect()'''
        self.wmCancel.setEnabled(False)
        self.wmCancel.clicked.connect(self.OptWMCancel)
        self.wmCancel.setFixedSize(120, 32)

        self.wmFrameLayoutDownPlaceHolder = QWidget()
        self.wmFrameLayoutDownPlaceHolder.setFixedHeight(36)

        self.wmFrameLayoutDown.addWidget(self.wmCancel)
        self.wmFrameLayoutDown.addWidget(self.wmFrameLayoutDownPlaceHolder)

        self.wmFrameLayout.addLayout(self.wmFrameLayoutUp)
        self.wmFrameLayout.addLayout(self.wmFrameLayoutDown)
        self.wmFrameLayout_asWidget.setLayout(self.wmFrameLayout)
        self.wmFrameLayout_asWidget.setFixedWidth(200)

    def ImageUIShow(self):

        self.demo_show_init = []

        '''self.imgToScale = QPixmap.fromImage(QImage('./img/Background_MainUI.jpg'))

        if self.imgToScale.width() > self.imgToScale.height():
            self.rate = int(self.imgToScale.width() / self.imgToScale.height())
            self.DemoScaled = self.imgToScale.scaled(self.rate * 375, 375, Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        else:
            self.rate = int(self.imgToScale.height() / self.imgToScale.width())
            self.DemoScaled = self.imgToScale.scaled(375, 375 * self.rate, Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        self.demo_show_init.append(self.DemoScaled)'''

    def ShowFunc(self):

        self.showFuncLayout = QHBoxLayout()
        self.showFuncLayout_asWidget = QWidget()
        self.showFuncLayout_asWidget.setFixedWidth(200)
        self.showFuncLayout.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.showFunBtn = QPushButton('设置')
        self.showFunBtn.setFixedSize(75, 32)
        self.showFunBtn.clicked.connect(self.showFunc)
        self.showFunStart = QPushButton('开始')
        self.showFunStart.setFixedSize(75, 32)
        self.showFunStart.clicked.connect(self.OptStart)
        self.showFunStart.setEnabled(False)
        self.showFuncLayout.addWidget(self.showFunBtn)
        self.showFuncLayout.addWidget(self.showFunStart)
        self.showFuncLayout_asWidget.setLayout(self.showFuncLayout)

    def StartFunc(self):

        self.path_redirected = './Images/Splash.png'

        self.startFuncs_asWidget = QWidget()
        self.startFuncs = QHBoxLayout()
        self.startFuncs.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        # 保存图片
        self.save_file = QPushButton("")
        self.save_file.setToolTip("设置保存路径")
        self.save_file.setStyleSheet(
            "QPushButton{border-image:url(%s/Images/Btn_LP_savefile.png);}"
            "QPushButton:pressed{border-image:url(%s/Images/Btn_LP_savefile.png);}"
            "QPushButton:disabled{border-image:url(%s/Images/Btn_LP_savefile_white.png);}"
        % (self.path_redirected, self.path_redirected, self.path_redirected))
        self.save_file.clicked.connect(self.save_image)
        self.save_file.setEnabled(False)
        self.save_file.setFixedSize(32, 32)

        # 开始操作
        self.opt_resume = QPushButton("")
        self.opt_resume.setToolTip("继续图像操作")
        self.opt_resume.setStyleSheet(
            "QPushButton{border-image:url(%s/Images/Btn_LP_fileoptstart.png);}"
            "QPushButton:pressed{border-image:url(%s/Images/Btn_LP_fileoptstart.png);}"
            "QPushButton:disabled{border-image:url(%s/Images/Btn_LP_fileoptstart_white.png);}"
        % (self.path_redirected, self.path_redirected, self.path_redirected))
        '''self.opt_start.clicked.connect(self.xxx)'''
        '''self.opt_start.clicked.connect()'''
        self.opt_resume.setEnabled(False)
        self.opt_resume.clicked.connect(self.OptResume)
        self.opt_resume.setFixedSize(32, 32)

        # 暂停操作
        self.opt_stop = QPushButton("")
        self.opt_stop.setToolTip("停止图像操作")
        self.opt_stop.setStyleSheet(
            "QPushButton{border-image:url(%s/Images/Btn_LP_fileoptstop.png);}"
            "QPushButton:pressed{border-image:url(%s/Images/Btn_LP_fileoptstop.png);}"
            "QPushButton:disabled{border-image:url(%s/Images/Btn_LP_fileoptstop_white.png);}"
        % (self.path_redirected, self.path_redirected, self.path_redirected))
        self.opt_stop.clicked.connect(self.OptPause)
        self.opt_stop.setEnabled(False)
        self.opt_stop.setFixedSize(32, 32)

        # 终止操作
        self.opt_terminate = QPushButton("")
        self.opt_terminate.setToolTip("终止图像操作")
        self.opt_terminate.setStyleSheet(
            "QPushButton{border-image:url(%s/Images/Btn_LP_fileoptterminate.png);}"
            "QPushButton:pressed{border-image:url(%s/Btn_LP_fileoptterminate.png);}"
            "QPushButton:disabled{border-image:url(%s/Btn_LP_fileoptterminate_white.png);}"
        % (self.path_redirected, self.path_redirected, self.path_redirected))
        self.opt_terminate.clicked.connect(self.OptTerminate)
        self.opt_terminate.setEnabled(False)
        self.opt_terminate.setFixedSize(32, 32)

        self.opt_status = QLineEdit()
        self.opt_status.setEnabled(False)
        self.opt_status.setFixedWidth(340)
        self.opt_status.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.opt_status.setText('请点击"设置"按钮，选择图片、设置水印选项、设置保存路径')

        self.startFuncs.addWidget(self.save_file)
        self.startFuncs.addWidget(self.opt_resume)
        self.startFuncs.addWidget(self.opt_stop)
        self.startFuncs.addWidget(self.opt_terminate)
        self.startFuncs.addWidget(self.opt_status)
        self.startFuncs_asWidget.setLayout(self.startFuncs)

    def ProgresBar(self):

        self.progressBarLayout = QHBoxLayout()
        self.progressBarLayout.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.progressBarLayout_asWidget = QWidget()

        self.progressBar = QProgressBar()
        self.progressBar.setFixedSize(160, 8)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(5)
        self.progressBar.setTextVisible(False)
        self.progressBar.setVisible(False)

        self.progressBarLayout.addWidget(self.progressBar)
        self.progressBarLayout_asWidget.setLayout(self.progressBarLayout)

    def LayoutImgSetup(self):

        self.DemoLayout = QVBoxLayout()
        self.ImgBtnsLayout = QHBoxLayout()
        self.ImgPanelLayout = QHBoxLayout()

        self.ImgBtnsLayout.addWidget(self.showFuncLayout_asWidget)
        self.ImgBtnsLayout.addWidget(self.startFuncs_asWidget)
        self.ImgBtnsLayout.addWidget(self.progressBarLayout_asWidget)
        self.ImgBtnsLayout_asWidget = QWidget()
        self.ImgBtnsLayout_asWidget.setLayout(self.ImgBtnsLayout)

        self.imgPanelLeft = QVBoxLayout()
        self.imgPanelLeft_asWidget = QWidget()
        self.imgPanelLeft.setAlignment(Qt.AlignCenter)
        self.imgPanelLeft.addWidget(self.imgFrameImglLayout_asWidget)
        self.imgPanelLeft.addWidget(self.imgLeftBoxLayout_asWidget)
        self.imgPanelLeft_asWidget.setLayout(self.imgPanelLeft)

        self.imgPanelRight = QVBoxLayout()
        self.imgPanelRight_asWidget = QWidget()
        self.imgPanelRight.setAlignment(Qt.AlignCenter)
        self.imgPanelRight.addWidget(self.imgFrameImgrLayout_asWidget)
        self.imgPanelRight.addWidget(self.imgRightBoxLayout_asWidget)
        self.imgPanelRight_asWidget.setLayout(self.imgPanelRight)

        self.ImgPanelLayout.setSpacing(0)
        self.ImgPanelLayout.addWidget(self.imgPanelLeft_asWidget)
        self.ImgPanelPlaceholder = QWidget()
        self.ImgPanelPlaceholder.setFixedSize(40, 480)
        self.ImgPanelPlaceholder.setStyleSheet('border-left:1px solid #2F2F2F;margin-top:5px;margin-bottom:20px;')
        self.ImgPanelLayout.addWidget(self.ImgPanelPlaceholder)
        self.ImgPanelLayout.addWidget(self.imgPanelRight_asWidget)
        self.ImgPanelLayout.addWidget(self.wmFrameLayout_asWidget)
        self.ImgPanelLayout_asWidget = QWidget()
        self.ImgPanelLayout_asWidget.setLayout(self.ImgPanelLayout)

        self.DemoLayout.addWidget(self.ImgBtnsLayout_asWidget)
        self.DemoLayout.addWidget(self.ImgPanelLayout_asWidget)

        self.setLayout(self.DemoLayout)

    ### 加水印槽函数

    def showFunc(self):

        self.Demo.show()

    def demonstrateImage(self, watermark_info):

        print(watermark_info)
        self.watermark_info.clear()
        self.info_img_path = watermark_info[0]
        self.info_wm_path = watermark_info[1]
        self.info_pos_index = watermark_info[2]
        self.info_opacity = watermark_info[3]
        self.info_scale = watermark_info[4]
        self.watermark_info = [self.info_img_path, self.info_wm_path, self.info_pos_index, self.info_opacity, self.info_scale]
        print(self.info_scale)
        print('数据已传送给全局变量' , self.watermark_info)

        if self.info_pos_index == 1:
            self.wm_pos = '左上角'
        elif self.info_pos_index == 2:
            self.wm_pos = '正上方'
        elif self.info_pos_index == 3:
            self.wm_pos = '右上角'
        elif self.info_pos_index == 4:
            self.wm_pos = '左侧中间'
        elif self.info_pos_index == 5:
            self.wm_pos = '正中心'
        elif self.info_pos_index == 6:
            self.wm_pos = '右侧中间'
        elif self.info_pos_index == 7:
            self.wm_pos = '左下角'
        elif self.info_pos_index == 8:
            self.wm_pos = '正下方'
        elif self.info_pos_index == 9:
            self.wm_pos = '右下角'

        self.info_opacity_str = str(int(100 * self.info_opacity)) + '%'
        self.info_scale_str = str(int(100 * self.info_scale)) + '%'

    def InitImgsList(self, imgList):

        print(imgList)
        self.imgFrameImgl.setText(('待处理图片：共%d张\n\n水印位置：%s\n\n水印透明度：%s\n\n水印大小：%s') % (
        len(imgList), self.wm_pos, self.info_scale_str, self.info_scale_str))
        self.opt_status.setText('待处理图片：共%d张，' % len(imgList) + '请先选择存储路径，再开始操作')
        self.imgList.clear()
        self.imgList = imgList
        self.save_file.setEnabled(True)
        if len(self.img_save_name) != 0:
            self.showFunStart.setEnabled(True)
        else:
            pass
        print(self.imgList)

    def open_image(self):
        self.update()
        self.img_info = QFileDialog.getOpenFileNames(self, "选择图片", "/" , "JPEG(*.jpg *.jpeg);;PNG(*.png);;TIFF(*.tiff);;BMP(*.bmp)")
        self.imgs = self.img_info[0]
        if len(self.img_info) > 0:
            self.update()
            for l in range(len(self.imgs)):
                self.img_bf_to_browse = self.imgs[0]
                img_name_item = QTableWidgetItem()
                img_name_item.setText(str(self.imgs[l]))
                img_status = QTableWidgetItem()
                img_status.setText('未处理')
                self.update()
        else:
            self.update()
            self.opt_resume.setEnabled(False)

    def save_image(self):
        self.update()
        self.img_save = QFileDialog.getSaveFileName(self, "保存文件", "/", "JPEG(*.jpg *.jpeg);;PNG(*.png);;TIFF(*.tiff);;BMP(*.bmp)")
        self.img_save_path, self.img_save_name = os.path.split(self.img_save[0])
        '''print(self.img_save_info.absolutePath())'''
        print(self.img_save_path)
        print(self.img_save_name)
        print(self.img_save[1])
        if len(self.img_save_name) == 0:
            self.setWindowTitle('图像批处理——添加水印')
            self.showFunStart.setEnabled(False)
            self.opt_status.setText('待处理图片：共%d张，' % len(self.imgList) + '请先选择存储路径，再开始操作')
        else:
            self.setWindowTitle('图像批处理——添加水印，保存文件夹为：' + str(self.img_save_path))
            self.showFunStart.setEnabled(True)
            self.opt_status.setText('待处理图片：共%d张，' % len(self.imgList) + '点击开始按钮，开始操作')
            self.imgFrameImgl.setText(('待处理图片：共%d张\n\n水印位置：%s\n\n水印透明度：%s\n\n水印大小：%s\n\n统一文件名结尾：%s') % (
                len(self.imgList), self.wm_pos, self.info_scale_str, self.info_scale_str, str(self.img_save_name)))

    def OptStart(self):

        imgs = self.imgList
        print(imgs)
        print(self.imgList)
        print(self.watermark_info)
        self.progressBar.setVisible(True)
        self.Wm_Start.WM_Info(self.imgList, self.watermark_info, self.img_save_path, self.img_save_name)
        self.Wm_Start.WM_Status('开始')
        self.Wm_Start.start()
        self.showFunBtn.setEnabled(False)
        self.showFunStart.setEnabled(False)
        self.save_file.setEnabled(False)
        self.opt_resume.setEnabled(False)
        self.opt_stop.setEnabled(True)
        self.opt_status.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

    def OptPause(self):

        self.opt_resume.setEnabled(True)
        self.opt_terminate.setEnabled(True)
        self.opt_stop.setEnabled(False)
        self.Wm_Start.pause.lock()

    def OptResume(self):

        self.opt_resume.setEnabled(False)
        self.opt_stop.setEnabled(True)
        self.opt_terminate.setEnabled(False)
        self.Wm_Start.pause.unlock()

    def OptTerminate(self):

        self.Wm_Start.pause.unlock()
        self.Wm_Start.WM_Status('终止')
        self.opt_status.setText('操作被终止  ')
        self.showFunBtn.setEnabled(True)
        self.showFunStart.setEnabled(True)
        self.save_file.setEnabled(True)
        self.opt_resume.setEnabled(False)
        self.opt_stop.setEnabled(False)
        self.opt_terminate.setEnabled(False)
        time.sleep(0.5)
        self.opt_status.setText('请点击"设置"按钮，选择图片、设置水印选项、设置保存路径')
        self.opt_status.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.update()

    def Progress(self, int):
        i = int
        self.opt_status.setText('正在处理第%d张图片  ' % i)

    def ProgressBarStatus(self, int):
        self.progressBar.setValue(int)

    def Finished(self, str):
        self.showFunBtn.setEnabled(True)
        self.showFunStart.setEnabled(False)
        self.save_file.setEnabled(True)
        self.opt_resume.setEnabled(False)
        self.opt_stop.setEnabled(False)
        self.opt_terminate.setEnabled(False)
        self.opt_status.setText('请点击"设置"按钮，选择图片、设置水印选项、设置保存路径')
        self.opt_status.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        if str == '操作结束':
            self.imgFrameImgl.setText('处理完成 ^_^')
            self.progressBar.setValue(0)
            self.progressBar.setVisible(False)
        else:
            self.imgFrameImgl.setText('处理被终止 o_O')
            self.progressBar.setValue(0)
            self.progressBar.setVisible(False)

    ### 转换水印槽函数

    def OptWMOpen(self):

        self.wm_before_list = QFileDialog.getOpenFileName(self, "打开水印", "/", "JPEG(*.jpg *.jpeg);;PNG(*.png)")
        self.wm_before = self.wm_before_list[0]
        print(self.wm_before)
        if len(self.wm_before) > 0:
            self.wmConvert.setEnabled(True)
            self.imgToScaleDemo = QPixmap.fromImage(QImage(self.wm_before))
            if self.imgToScaleDemo.width() > self.imgToScaleDemo.height():
                self.rateDemo = self.imgToScaleDemo.width() / self.imgToScaleDemo.height()
                self.DemoScaledBefore = self.imgToScaleDemo.scaled(375, int(375 / self.rateDemo), Qt.KeepAspectRatio,
                                                         Qt.SmoothTransformation)
            else:
                self.rateDemo = self.imgToScaleDemo.height() / self.imgToScaleDemo.width()
                self.DemoScaledBefore = self.imgToScaleDemo.scaled(int(375 / self.rateDemo), 375, Qt.KeepAspectRatio,
                                                         Qt.SmoothTransformation)
            self.imgFrameImgr.setPixmap(self.DemoScaledBefore)
            print(self.DemoScaledBefore.width(), self.DemoScaledBefore.height())
            self.wmCancel.setEnabled(True)
        else:
            self.wmConvert.setEnabled(False)

    def OptWMConvert(self):

        self.Wm_Convert.wm_data(self.wm_before, 0, None)
        self.wmConvProgress.setVisible(True)
        self.Wm_Convert.start()
        self.wmOpen.setEnabled(False)
        self.wmSave.setEnabled(True)
        self.wmCancel.setEnabled(True)

    def OptWMSave(self):

        self.wm_conv_list = QFileDialog.getSaveFileName(self, "选择图片", "/", "JPEG(*.jpg *.jpeg);;TIFF(*.tiff);;BMP(*.bmp)")
        self.wm_conv = self.wm_conv_list[0]
        if len(self.wm_conv) > 0:
            self.Wm_Convert.wm_data(self.wm_before, 1, self.wm_conv)
            self.Wm_Convert.start()
            self.wmConvProgress.setVisible(True)
            self.wmOpen.setEnabled(True)
            self.wmSave.setEnabled(False)
            self.wmCancel.setEnabled(False)
        else:
            pass

    def OptWMCancel(self):

        self.imgFrameImgr.clear()
        self.wmOpen.setEnabled(True)
        self.wmSave.setEnabled(False)
        self.wmConvert.setEnabled(False)
        self.wmCancel.setEnabled(False)
        self.wmConvStatus.setText('未添加水印')


    def OptWMDemo(self, array):

        self.imgQt = QImage(array.data, array.shape[1], array.shape[0],
                            QImage.Format_BGR888)
        self.imgToScale = QPixmap.fromImage(self.imgQt)

        if self.imgToScale.width() > self.imgToScale.height():
            self.rate = self.imgToScale.width() / self.imgToScale.height()
            self.DemoScaled = self.imgToScale.scaled(375, int(375 / self.rate), Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        else:
            self.rate = self.imgToScale.height() / self.imgToScale.width()
            self.DemoScaled = self.imgToScale.scaled(int(375 / self.rate), 375, Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        self.imgFrameImgr.setPixmap(self.DemoScaled)

    def OptWMProgress(self, value, code):

        self.wmConvProgress.setValue(value)
        if code == 0:
            self.wmConvStatus.setText('水印已转换')
        else:

            self.wmConvStatus.setText('水印已保存')
        self.wmConvProgress.setVisible(False)

###### 业务逻辑线程
### 线程1：加水印
class WM_Operation_start(QThread):

    WM_Signal = pyqtSignal(int)
    WM_Progress_signal = pyqtSignal(int)
    WM_Stop_Signal = pyqtSignal(str)

    def __init__(self):
        super(WM_Operation_start, self).__init__()
        self.status = '开始'
        self.pause = QMutex()

    def WM_Info(self, imgList, watermark_info, img_save_path, img_save_name):
        self.imgList = []
        self.imgList.clear()
        for i in range(len(imgList)):
            self.imgList.append(imgList[i])
        self.info = []
        self.info.clear()
        for j in range(len(watermark_info)):
            self.info.append(watermark_info[j])
        self.save_path = img_save_path
        self.save_name = img_save_name

    def WM_Status(self, str):
        self.status = str

    def run(self):
        for l in range(len(self.imgList)):
            if self.status == '开始':
                self.pause.lock()
                self.WM_Signal.emit(l + 1)
                self.WM_Progress_signal.emit(1)
                self.imgShow_cv = funcWM.WaterMark().watermark(self.imgList[l], self.info[1], self.info[2],
                                                               self.info[3],
                                                               self.info[4])
                # self.imgShow_cv_rgb = cv2.cvtColor(self.imgShow_cv, cv2.COLOR_RGB2BGR)
                # cv2.imwrite(self.demo_show_path, self.imgShow_cv)
                self.WM_Progress_signal.emit(2)
                self.dir = str(self.save_path) + '/' + '{:0>3d}'.format(l+1) + '_' + str(self.save_name)
                self.WM_Progress_signal.emit(3)
                cv2.imwrite(self.dir, self.imgShow_cv, [int(cv2.IMWRITE_JPEG_QUALITY), 100])#这是保证质量的好办法
                self.WM_Progress_signal.emit(4)
                self.WM_Progress_signal.emit(5)
                self.pause.unlock()
            else:
                self.WM_Stop_Signal.emit('操作终止')
                self.quit()
        if self.status == '终止':
            self.WM_Stop_Signal.emit('操作终止')
        else:
            self.WM_Stop_Signal.emit('操作结束')
        self.quit()

### 线程2：转换水印
class WM_Convert(QThread):

    wm_as_array = pyqtSignal(np.ndarray)
    wm_pbvalue_n_optcode = pyqtSignal(int, int)

    def __del__(self):
        super(WM_Convert, self).__init__()

    def wm_data(self, wm_src, optCode, wmSavePath):
        self.wm_src = wm_src
        self.optCode = optCode
        self.savePath = wmSavePath

    def run(self):
        self.wm_pbvalue_n_optcode.emit(1, self.optCode)
        self.wm_after = wmConv.WM_Convert(self.wm_src)
        self.wm_pbvalue_n_optcode.emit(2, self.optCode)
        if self.optCode == 0:
            if self.wm_after.shape[1] % 4 != 0:
                self.wm_rate = self.wm_after.shape[0] / self.wm_after.shape[1]
                self.wm_width = int(self.wm_after.shape[1] - (self.wm_after.shape[1] % 4))
                self.wm_height = int(self.wm_width * self.wm_rate)
                self.wm_cv_resized = cv2.resize(self.wm_after, (self.wm_width, self.wm_height))
            else:
                self.wm_cv_resized = self.wm_after
            self.data = np.array(self.wm_cv_resized)
            self.wm_as_array.emit(self.data)
        else:
            cv2.imwrite(self.savePath, self.wm_after)
        self.wm_pbvalue_n_optcode.emit(3, self.optCode)
        self.exit(0)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    icon = QIcon('./Images/Splash.png')
    app.setWindowIcon(icon)
    qssStyle = '''
        QPushButton{
            background:#3D3D3D;
            color: #FFFFFF;
            font-family:;
            padding-left:10px;
            padding-right:10px;
            border-radius:4px;
            border:1px solid #9E9E9E;
        }
        QPushButton:disabled{
            background:#555555;
            color:#EEEEEE;
        }
        QPushButton:pressed{
            border:1px solid #EEEEEE;
        }
        QLineEdit:disabled{
            background:transparent;
            border:0px;
            color:#FFFFFF;
        }
        QTextEdit:disabled{
            background:transparent;
            border:0px;
            color:#FFFFFF;
        }
        QLabel:disabled{
            color:#FFFFFF;
        }
        QSlider::handle{
            width:6px;
            margin:-4px;
            padding-left:3px;
            padding-right:3px;
            background-color:#FFFFFF;
            border-radius:2px;
        }
        QSlider::groove:horizontal{
            height: 4px;
            padding-left:10px;
            padding-right:10px;
            background: #FFFFFF;
            border-radius:2px;
        }
        QSlider::sub-page:horizontal{
            height: 4px;
            background: qlineargradient(x1:0, x2:1, stop:0 #C5FFA1, stop:1 #69F6B7);
            border-radius:2px;
        }
        QSlider::add-page:horizontal{
            height: 4px;
            background: #808080;
            border: 0px solid #777;
            border-radius:2px;
        }
        QComboBox{
            background:#3D3D3D;
            color:#FFFFFF;
            border-radius:4px;
        }
        QComboBox::drop-down{
            background:#3D3D3D;
            color:#FFFFFF;
            border-radius:4px;
            border:0px;
            width:32px;
        }
        QComboBox::down-arrow{
            border-image:url(./Images/Btn_dropdown.png);
        }
        QComboBox:hover{
            background:#3D3D3D;
            color:#FFFFFF;
            border-radius:4px;
            border:0px;
        }
        QComboBox:hover:checked{
            background:#3D3D3D;
            color:#FFFFFF;
            border-radius:4px;
            border:0px;
        }
        QComboBox:off{
            background:#3D3D3D;
            color:#FFFFFF;
            border-radius:4px;
            border:0px;
        }
        QComboBox:disabled{
            background:#555555;
            color:#EEEEEE;
        }
        QRadioButton{
            margin-left:4px;
            padding-right:4px;
            color:#FFFFFF;
        }
        QTabWidget::tab-bar{border-width:0px;align-center;}
        QTabBar::tab{
            background: #3D3D3D;
            color:#FFFFFF;
            margin: 0;
            padding-left:12px;
            padding-right:12px;
            padding-top:4px;
            padding-bottom:4px;
        }
        QTabBar::tab:selected{
            background:qlineargradient(x1:0, x2:1, stop:0 #C5FFA1, stop:1 #69F6B7);
            color:#000000;
            margin: 0;
            border-radius:4px;
            padding-left:12px;
            padding-right:12px;
            padding-top:8px;
            padding-bottom:8px;
        }
        QHeaderView{
            background:#808080;
            color:#FFFFFF;
            padding-left:4px;
            border:0px;
        }
        QHeaderView::section{
            background:#808080;
            color:#FFFFFF;
            border:0px;
        }
        QTableWidget{
            background:#3D3D3D;
            color:#FFFFFF;
            border:0px;
            border-radius:4px;
        }
        QTableWidget::item{
            border:0px;
        }
        QTableWidget::item::selected{
            background:#FFFFFF;
            color:#000000;
            border:0px;
        }
        QProgressBar{
            background-color:#3D3D3D;
            text-align:center;
            border:none;
            border-radius:3px;
            margin-bottom:2px;
        }
        QProgressBar::enabled{
            border-radius:3px;
            color:#FFFFFF;
        }
        QProgressBar::chunk{
            border-radius:3px;
        }
        QProgressBar::chunk::enabled{
            background:qlineargradient(x1:0, x2:1, stop:0 #C5FFA1, stop:1 #69F6B7);
            border-radius:3px;
        }
    '''
    app.setStyleSheet(qssStyle)
    app.setFont(QFont("Source Han Sans SC"))
    splash_img = QImage('./Images/Splash.png')
    splash = QSplashScreen(QPixmap.fromImage(splash_img))
    splash.show()
    box = Watermark_Demo_UI()
    palette = QPalette()
    palette.setColor(QPalette.Background, QColor(74, 74, 74))
    box.setPalette(palette)
    app.processEvents()
    splash.finish(box)
    box.show()
    sys.exit(app.exec_())
    input()
